% B2_split_wrf.m 9/27/2011 Parker MacCready
%
% this splits up the results of the extraction code so that it is easier
% to process later (especially critical for the hourly output)

clear

% *** USER DEFINED VALUES **********************
dth = 120; % time step for forcing fields (hours) [120, 12, 3, 1]
period_list = {'wrf1'};
% *** END USER DEFINED VALUES ******************

switch dth
    case 120
        indir0 = 'extractions_five_day/';
    case 12
        indir0 = 'extractions_half_day/';
    case 3
        indir0 = 'extractions_three_hour/';
    case 1
        indir0 = 'extractions_hourly/';
    otherwise
        disp('that dth is not coded for')
        break
end

g_list = {'d2';'d3'};

% create the output directory
outdir0 = strrep(indir0,'extractions','split');
if ~(exist(outdir0,'dir')==7); mkdir(outdir0); end

for pp = 1:length(period_list)
    period = period_list{pp};
    disp(['period = ',period])
    
    indir = [indir0,period,'/'];
    
    outdira = [outdir0,period,'a/'];
    if ~(exist(outdira,'dir')==7); mkdir(outdira); end
    
    outdirb = [outdir0,period,'b/'];
    if ~(exist(outdirb,'dir')==7); mkdir(outdirb); end
    
    for gg = 1:length(g_list)
        g_tag = g_list{gg};
        
        varlist = {'psfc';'rainc';'swdown';'glw';'t2';'q2';'u10';'v10'};
        for vv = 1:length(varlist)
            var = varlist{vv};
            
            % save the first half in outdira
            load([indir,var,'_',g_tag,'.mat']);
            [NT] = length(tdvec);
            nn = round(NT/2);
            outmat = outmat(1:nn,:,:);
            tdvec = tdvec(1:nn);
            ts1_vec = ts1_vec(1:nn);
            ts2_vec = ts2_vec(1:nn);
            flag_file_exists = flag_file_exists(1:nn);
            save([outdira,var,'_',g_tag,'.mat'],'lon','lat','tdvec', ...
                'ts1_vec','ts2_vec','outmat', ...
                'flag_file_exists','-v7.3');
            
            % save the second half in outdirb
            load([indir,var,'_',g_tag,'.mat']);
            [NT] = length(tdvec);
            nn = round(NT/2);
            outmat = outmat(nn+1:end,:,:);
            tdvec = tdvec(nn+1:end);
            ts1_vec = ts1_vec(nn+1:end);
            ts2_vec = ts2_vec(nn+1:end);
            flag_file_exists = flag_file_exists(nn+1:end);
            save([outdirb,var,'_',g_tag,'.mat'],'lon','lat','tdvec', ...
                'ts1_vec','ts2_vec','outmat', ...
                'flag_file_exists','-v7.3');
            
        end
        
    end % end of gg loop
    
end


